import axios from 'axios'
import { ElMessage } from 'element-plus'
import { localGet } from './index'

// 创建axios实例
const service = axios.create({
  baseURL: '/api',
  timeout: 60000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localGet('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    if (res.status === 200 || res.status === 0) {
      return res
    } else {
      // 登录失效
      if (res.status === 401) {
        ElMessage.error('登录失效，请重新登录')
        // 清除token并跳转到登录页
        localStorage.removeItem('token')
        window.location.href = '#/login'
        return Promise.reject(new Error(res.message || 'Error'))
      } else {
        ElMessage.error(res.message || 'Error')
        return Promise.reject(new Error(res.message || 'Error'))
      }
    }
  },
  error => {
    console.log('err' + error)
    let message = error.message
    if (error.response) {
      if (error.response.status === 401) {
        message = '登录失效，请重新登录'
        localStorage.removeItem('token')
        window.location.href = '#/login'
      } else if (error.response.status === 403) {
        message = '拒绝访问'
      } else if (error.response.status === 404) {
        message = '请求地址出错'
      } else if (error.response.status === 408) {
        message = '请求超时'
      } else if (error.response.status === 500) {
        message = '服务器内部错误'
      } else if (error.response.status === 501) {
        message = '服务未实现'
      } else if (error.response.status === 502) {
        message = '网关错误'
      } else if (error.response.status === 503) {
        message = '服务不可用'
      } else if (error.response.status === 504) {
        message = '网关超时'
      } else if (error.response.status === 505) {
        message = 'HTTP版本不受支持'
      }
    }
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

export default service